<template>
  <div class="wh-gaode-wraper" id="geodeMap"></div>
</template>

<script>
import { path } from '@antv/x6/lib/registry/marker/path';
import AMapLoader from '../common/gaodeLoader.js'
// import AMapLoader from "@amap/amap-jsapi-loader"
export default {
  data() {
    return {
      AMap: null,
      map: null,
      markerList: [],
      navgList: []
    }
  },
  methods: {
    loadMap(options) {
      console.log('创建高德地图');
      return new Promise((resolve, reject) => {
        if(!options.loadConfig) {
          console.error('未配置地图加载所需的必要配置');
          reject('未配置地图加载所需的必要配置')
        }
        if (options.loadConfig.securityJsCode) {
          // 高德地图key的密钥
          window._AMapSecurityConfig = {
            securityJsCode: options.securityJsCode // 密钥
          }
        } else {
          console.warn('未配置高德key的密钥')
        }
        var config = {}
        if (options.loadConfig.key) {
          config = {
            key: options.loadConfig.key,
            version: options.loadConfig.version,
            AMapUI: options.loadConfig.AMapUI,
            Loca: options.loadConfig.Loca
          }
        } else {
          console.warn('未配置高德key')
          reject('未配置高德key')
        }
        if (options.loadConfig.offline) {
          if (!options.loadConfig.tileUrl) {
            console.warn('未配置离线地址')
            reject('未配置离线地址')
          }
        }
        AMapLoader.load({
          ...config
          // version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
          // AMapUI: {
          //   // 是否加载 AMapUI，缺省不加载
          //   version: '1.1', // AMapUI 缺省 1.1
          //   plugins: [] // 需要加载的 AMapUI ui插件
          // },
          // Loca: {
          //   // 是否加载 Loca， 缺省不加载
          //   version: '2.0.0' // Loca 版本，缺省 1.3.2
          // }
        }).then((AMap) => {
          // 标准normal
          // 幻影黑dark
          // 月光银light
          // 远山黛whitesmoke
          // 草色青fresh
          // 雅士灰grey
          // 涂鸦graffiti
          // 马卡龙macaron
          // 靛青蓝blue
          // 极夜蓝darkblue
          // 酱籽wine
          this.AMap = AMap
          const gaodeMapLayer = new AMap.TileLayer({
            getTileUrl: options.loadConfig.tileUrl,
            opacity: 1,
            zIndex: 9
          })
          // : new AMap.createDefaultLayer({
          //   // zooms: [3,20],    // 可见级别
          //   visible: true,    // 是否可见
          //   opacity: 1,       // 透明度
          //   zIndex: 0         // 叠加层级
          // })
          this.map = new AMap.Map('geodeMap', {
            layers: options.loadConfig.offline?[gaodeMapLayer]:null,
            ...options.mapConfig
          })
          this.map.on('click', this.onClickMap)
          resolve(this.map)
        }).catch(e => {
          reject(e)
        })
      })
    },
    loadMarker (markerList) {
      console.log('加载 marker');
      var markers = []
      for (var i = 0; i < markerList.length; i++) {
        var markerOptions = markerList[i].options?markerList[i].options:{}
        var size = [markerOptions.width || 28, markerOptions.height || 28]
        var offfset = new AMap.Pixel(-size[0]/2, -size[1])
        var icon = new AMap.Icon({
          image: markerOptions.icon || require('../assets/marker/marker-6.png'),
          size: new AMap.Size(size[0], size[1]),
          imageSize: new AMap.Size(size[0], size[1])
        })
        markerOptions.icon = icon
        markerOptions.zIndex = markerOptions.zIndex || 12
        markerOptions.opacity = markerOptions.opacity || 1
        markerOptions.offset = offfset
        console.log(markerOptions);
        var marker = new AMap.Marker({
          position: markerList[i].position,
          extData: markerList[i].extData,
          ...markerOptions
        });
        marker.on('click', this.onClickMarker)
        markers.push(marker)
      }
      this.markerLayer = new AMap.OverlayGroup(markers)
      this.map.add(this.markerLayer)
    },
    loadPolygon (polygonList) {
      console.log('加载多边形');
      var polygons = []
      // cursor: polygonList[i].polygonOptions.cursor || 'cursor',
      // strokeColor: polygonList[i].polygonOptions.strokeColor || '#00D3FC',
      // strokeOpacity: polygonList[i].polygonOptions.strokeOpacity || 0.9,
      // strokeWeight: polygonList[i].polygonOptions.strokeWeight || 2,
      // fillColor: polygonList[i].polygonOptions.fillColor || '#00B2D5',
      // fillOpacity: polygonList[i].polygonOptions.fillOpacity || 0.5,
      // extrusionHeight: polygonList[i].polygonOptions.extrusionHeight || 0,
      // height: polygonList[i].polygonOptions.height || 0,
      // wallColor: polygonList[i].polygonOptions.wallColor || '#00D3FC',
      // roofColor: polygonList[i].polygonOptions.roofColor || '#00D3FC',
      // strokeStyle: polygonList[i].polygonOptions.strokeStyle || 'solid',
      // strokeDasharray: polygonList[i].polygonOptions.strokeDasharray || [],
      // zIndex: polygonList[i].polygonOptions.zIndex || 10,
      // bubble: polygonList[i].polygonOptions.bubble || false
      for (var i = 0; i < polygonList.length; i++) {
        var polygonOptions = polygonList[i].options?polygonList[i].options:{}
        polygonOptions.strokeColor = polygonOptions.lineColor || '#00B2D5'
        polygonOptions.strokeWeight = polygonOptions.lineWidth || 2
        polygonOptions.strokeOpacity = polygonOptions.lineOpacity || 1
        polygonOptions.strokeStyle = polygonOptions.lineStyle || 'solid'
        polygonOptions.fillColor = polygonOptions.color || '#00B2D5'
        polygonOptions.fillOpacity = polygonOptions.opacity || 0.5
        polygonOptions.zIndex = polygonOptions.zIndex || 10
        var polygon = new AMap.Polygon({
          path: polygonList[i].path,
          extData: polygonList[i].extData,
          ...polygonOptions
        })
        polygon.on('click', this.onClickPolygon)
        polygons.push(polygon)
      }
      this.polygonLayer = new AMap.OverlayGroup(polygons)
      this.map.add(this.polygonLayer)
    },
    loadPath (config) {

      AMapUI.load(['ui/misc/PathSimplifier', 'ui/overlay/SimpleMarker'], (PathSimplifier, SimpleMarker) => {

        if (!PathSimplifier.supportCanvas) {
            alert('当前环境不支持 Canvas！');
            return;
        }
        var arr = config.list?config.list:[{
            name: '路线1',
            path: PathSimplifier.getGeodesicPath([116.405289, 39.904987], [87.61792, 43.793308], 100)
        },{
            name: '路线2',
            path: PathSimplifier.getGeodesicPath([112.230863,37.485232], [108.891019,34.208985], 100)
        }, {
            name: '路线3',
            path: PathSimplifier.getGeodesicPath([118.866605,32.075034], [104.10098,30.346236], 100)
        }, {
            name: '路线4',
            path: PathSimplifier.getGeodesicPath([101.596097,36.608384], [109.63809,37.135709], 100)
        }]
        let options = config.options?config.options:{}
        //  线条样式
        var pathStyle = {
          color: 'red',
          width: 5,
          defaultColor: '#00D3FC',
          speed: 80 // m/s
        }
        if (options.line && options.line.defaultColor) {
          pathStyle.defaultColor = options.line.defaultColor
        }
        if (options.line && options.line.width) {
          pathStyle.width = options.line.width
        }
        if (options.line && options.line.color) {
          pathStyle.color = options.line.color
        }
        if (options.speed) {
          pathStyle.speed = options.speed
        }
        var pathSimplifierIns = new PathSimplifier({
            zIndex: 100,
            autoSetFitView:false,
            map: this.map, //所属的地图实例
            data: arr,
            // pathClick: false,
            // clickToSelectPath: false,
            getPath: (pathData, pathIndex) => {
              let startPosition = pathData.path[0]
              let endPosition = pathData.path[pathData.path.length-1]
              // 起点
              var startSymbol = {
                icon: require('../assets/marker/start.png'),
                width: 28,
                height: 28
              }
              if (options.start && options.start.icon) {
                startSymbol.icon = options.start.icon
              }
              if (options.start && options.start.width) {
                startSymbol.width = options.start.width
              }
              if (options.start && options.start.height) {
                startSymbol.height = options.start.height
              }
              let startIcon = new AMap.Icon({
                // 图标尺寸
                size: new AMap.Size(startSymbol.width, startSymbol.height),
                // 图标的取图地址
                image: startSymbol.icon,
                imageSize: new AMap.Size(startSymbol.width, startSymbol.height)
              });
              let startMarker = new AMap.Marker({
                position: startPosition,
                icon: startIcon,
                map: this.map,
                offset: new AMap.Pixel(-startSymbol.width/2, -startSymbol.height)
              });

              startMarker.on('click', (e) => {
                this.navgList[pathIndex].start()
              })
              // let endMarker = new SimpleMarker({
              //   //普通文本
              //   iconLabel: {
              //     //普通文本
              //     innerHTML: '终',
              //     //设置样式
              //     style: {
              //       color: '#fff',
              //       fontSize: '100%',
              //       marginTop: '2px'
              //     }
              //   },
              //   iconStyle: 'red',
              //   map:  this.map,
              //   position: endPoint
              // });
              // 终点
              var endSymbol = {
                icon: require('../assets/marker/end.png'),
                width: 28,
                height: 28
              }
              if (options.end && options.end.icon) {
                endSymbol.icon = options.end.icon
              }
              if (options.end && options.end.width) {
                endSymbol.width = options.end.width
              }
              if (options.end && options.end.height) {
                endSymbol.height = options.end.height
              }
              let endIcon = new AMap.Icon({
                // 图标尺寸
                size: new AMap.Size(endSymbol.width, endSymbol.height),
                // 图标的取图地址
                image: endSymbol.icon,
                imageSize: new AMap.Size(endSymbol.width, endSymbol.height)
              });
              let endMarker = new AMap.Marker({
                position: endPosition,
                icon: endIcon,
                map: this.map,
                offset: new AMap.Pixel(-endSymbol.width/2, -endSymbol.height)
              });

              return pathData.path;
            },
            getHoverTitle: (pathData, pathIndex, pointIndex) => {
              console.log(pathData);
              if (pointIndex === 0) {
                return pathData.properties.name+'：起点'
              } else if (pointIndex === pathData.path.length - 1) {
                return pathData.properties.name+'：终点'
              } else {
                return pathData.properties.name;
              }
            },
            renderOptions: config.options1?config.options:{
              renderAllPointsIfNumberBelow: -1,
              pathTolerance: 2,
              eventSupportInvisible: false,
              eventSupport: false,
              keyPointTolerance: 0,
              pathLineStyle: {
                  // lineWidth: 3,
                  // strokeStyle: '#F7B538',
                  // borderWidth: 1,
                  // borderStyle: '#eeeeee',
                  // dirArrowStyle: false,
                  lineWidth: pathStyle.width,
                  strokeStyle: pathStyle.defaultColor,
                  borderWidth: 1,
                  borderStyle: '#cccccc',
                  dirArrowStyle: true
              },
              pathLineHoverStyle: {
                  lineWidth: pathStyle.width,
                  strokeStyle: pathStyle.defaultColor,
                  borderWidth: 1,
                  borderStyle: '#cccccc',
                  dirArrowStyle: false
              },
              pathLineSelectedStyle: {
                  lineWidth: pathStyle.width,
                  strokeStyle: pathStyle.defaultColor,
                  borderWidth: 1,
                  borderStyle: '#cccccc',
                  dirArrowStyle: true
              },
              dirArrowStyle: {
                  stepSpace: 20,
                  strokeStyle: '#ffffff',
                  lineWidth: 2
              },
              startPointStyle: {
                  radius: 0,
                  fillStyle: '#109618',
                  lineWidth: 1,
                  strokeStyle: '#eeeeee'
              },
              endPointStyle: {
                  radius: 0,
                  fillStyle: '#dc3912',
                  lineWidth: 1,
                  strokeStyle: '#eeeeee'
              },
              keyPointStyle: {
                  radius: 0,
              },
              keyPointHoverStyle: {
                  radius: 0,
              },
              keyPointOnSelectedPathLineStyle: {
                  radius: 0,
              }
            }
        });

        //对第一条线路（即索引 0）创建一个巡航器
        var pointSymbol = {
          icon: require('../assets/marker/car.png'),
          width: 28,
          height: 28
        }
        if (options.point && options.point.icon) {
          pointSymbol.icon = options.point.icon
        }
        if (options.point && options.point.width) {
          pointSymbol.width = options.point.width
        }
        if (options.point && options.point.height) {
          pointSymbol.height = options.point.height
        }
        for (var i = 0; i < arr.length; i++) {
          var navg = pathSimplifierIns.createPathNavigator(i, {
              loop: false, //循环播放
              speed: pathStyle.speed * 3.6,//巡航速度，单位千米/小时
              pathNavigatorStyle: {
                width: pointSymbol.width,
                height: pointSymbol.height,
                pathLinePassedStyle: {
                  lineWidth: pathStyle.width,
                  strokeStyle: pathStyle.color,
                  borderWidth: 1,
                  borderStyle: '#cccccc',
                  dirArrowStyle: true
                },
                //使用图片
                content: PathSimplifier.Render.Canvas.getImageContent(pointSymbol.icon, function onload(){
                  pathSimplifierIns.renderLater();
                }, function onerror(e) {
                  console.log('图片加载失败：', e);
                }),
              },

          });
          this.navgList.push(navg)

        }
      });

    },
    onClickMarker (e) {
      this.$emit('on-click-marker', e.target, e.target.getExtData())
    },
    onClickPolygon (e) {
      this.$emit('on-click-polygon', e.target, e.target.getExtData())
    },
    onClickMap (e) {
      this.$emit('on-click-map', e)
    }
  },

}
</script>

<style scoped>
  .wh-gaode-wraper {
    width: 100%;
    height: 100%;
  }
  >>> .amap-logo {
    display: none !important;
  }
  >>> .amap-copyright {
    display: none !important;
  }
</style>
